import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import './PhotoPreview.css';

const PhotoPreview = ({ photos, currentIndex, onClose }) => {
  const { t } = useTranslation();
  const [isLoading, setIsLoading] = useState(true);
  const [imageError, setImageError] = useState(false);
  const [isLivePhoto, setIsLivePhoto] = useState(false);
  const [isPlayingLivePhoto, setIsPlayingLivePhoto] = useState(false);

  const photo = photos && photos.length > 0 && currentIndex >= 0 && currentIndex < photos.length ? photos[currentIndex] : null;
  
  useEffect(() => {
    setIsLoading(true);
    setImageError(false);
    setIsLivePhoto(false);
    setIsPlayingLivePhoto(false);
  }, [photo]);

  const handleImageLoad = () => {
    setIsLoading(false);
  };

  const handleImageError = () => {
    setIsLoading(false);
    setImageError(true);
  };

  const [currentPhotoIndex, setCurrentPhotoIndex] = useState(currentIndex || 0);
  
  const handleKeyDown = (e) => {
    if (e.key === 'Escape') onClose();
    if (e.key === 'ArrowRight' && hasNext()) nextPhoto();
    if (e.key === 'ArrowLeft' && hasPrev()) prevPhoto();
  };

  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [onClose]);
  
  const nextPhoto = () => {
    if (hasNext()) {
      setCurrentPhotoIndex(prev => prev + 1);
    }
  };
  
  const prevPhoto = () => {
    if (hasPrev()) {
      setCurrentPhotoIndex(prev => prev - 1);
    }
  };
  
  const hasNext = () => {
    return photos && currentPhotoIndex < photos.length - 1;
  };
  
  const hasPrev = () => {
    return photos && currentPhotoIndex > 0;
  };
  
  // Update current photo when currentIndex prop changes
  useEffect(() => {
    if (currentIndex !== undefined && currentIndex !== currentPhotoIndex) {
      setCurrentPhotoIndex(currentIndex);
    }
  }, [currentIndex, currentPhotoIndex]);

  const isVideo = photo && photo.name && (photo.name.toLowerCase().endsWith('.mp4') ||
                               photo.name.toLowerCase().endsWith('.webm') ||
                               photo.name.toLowerCase().endsWith('.mov'));
  
  const isGif = photo && photo.name && photo.name.toLowerCase().endsWith('.gif');
  
  // Check if it's a Live Photo (Apple's format)
  const checkIfLivePhoto = () => {
    if (photo && photo.name && photo.name.toLowerCase().endsWith('.jpg')) {
      // In a real app, you would check for additional metadata or a companion video file
      // For demo purposes, we'll randomly mark some JPGs as Live Photos
      setIsLivePhoto(photo.name.includes('live') || Math.random() > 0.7);
    }
  };
  
  useEffect(() => {
    checkIfLivePhoto();
  }, [photo]);
  
  const toggleLivePhoto = () => {
    if (isLivePhoto) {
      setIsPlayingLivePhoto(!isPlayingLivePhoto);
    }
  };

  return (
    <div className="photo-preview-overlay" onClick={onClose}>
      <div className="photo-preview-container" onClick={(e) => e.stopPropagation()}>
        <button className="photo-preview-close" onClick={onClose} aria-label="Close">
          ×
        </button>
        
        {hasPrev() && (
          <button className="photo-preview-nav prev" onClick={prevPhoto} aria-label="Previous">
            ‹
          </button>
        )}
        
        {hasNext() && (
          <button className="photo-preview-nav next" onClick={nextPhoto} aria-label="Next">
            ›
          </button>
        )}
        
        <div className="photo-preview-content">
          {isLoading && (
            <div className="photo-preview-loading">
              <div className="loading-spinner"></div>
              <p>{t('albums.loading')}</p>
            </div>
          )}
          
          {imageError ? (
            <div className="photo-preview-error">
              <div className="error-icon">⚠️</div>
              <p>{t('albums.photoLoadError')}</p>
            </div>
          ) : (
            photo ? (
              <div className="photo-preview-media">
                {isVideo ? (
                  <video
                    className="photo-preview-video"
                    controls
                    autoPlay
                    onLoadedData={handleImageLoad}
                    onError={handleImageError}
                  >
                    <source src={photo.thumbnail} type="video/mp4" />
                    {t('albums.videoNotSupported')}
                  </video>
                ) : (
                  <div className={`photo-preview-image-container ${isLivePhoto ? 'live-photo' : ''}`}>
                    <img
                      className={`photo-preview-image ${isGif ? 'gif' : ''} ${isPlayingLivePhoto ? 'live-playing' : ''}`}
                      src={photo.thumbnail}
                      alt={photo.name}
                      onLoad={handleImageLoad}
                      onError={handleImageError}
                      style={{ display: isLoading ? 'none' : 'block' }}
                      onClick={toggleLivePhoto}
                    />
                    {isLivePhoto && (
                      <div className="live-photo-indicator" onClick={toggleLivePhoto}>
                        <div className="live-photo-icon">
                          {isPlayingLivePhoto ? '⏸️' : '▶️'}
                        </div>
                        <div className="live-photo-text">
                          {isPlayingLivePhoto ? t('albums.pauseLivePhoto') : t('albums.playLivePhoto')}
                        </div>
                      </div>
                    )}
                    {isLivePhoto && isPlayingLivePhoto && (
                      <div className="live-photo-animation">
                        <div className="live-photo-effect"></div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            ) : (
              <div className="photo-preview-error">
                <div className="error-icon">⚠️</div>
                <p>{t('albums.photoLoadError')}</p>
              </div>
            )
          )}
          
          <div className="photo-preview-info">
            <h3 className="photo-preview-title">{photo ? photo.name : ''}</h3>
            <p className="photo-preview-date">{photo ? photo.date : ''}</p>
            {photo && photo.albumName && (
              <p className="photo-preview-album">{t('albums.photoFromAlbum')}: {photo.albumName}</p>
            )}
            {photos && photos.length > 1 && (
              <p className="photo-preview-counter">{currentPhotoIndex + 1} / {photos.length}</p>
            )}
          </div>
        </div>
        
        <div className="photo-preview-actions">
          <button className="photo-preview-action" title={t('albums.sharePhoto')}>
            🔗
          </button>
          <button className="photo-preview-action" title={t('albums.deletePhoto')}>
            🗑️
          </button>
          <button className="photo-preview-action" title={t('albums.downloadPhoto')}>
            ⬇️
          </button>
        </div>
      </div>
    </div>
  );
};

export default PhotoPreview;